package com.at.filter;


import com.alibaba.fastjson.JSON;
import com.at.common.BaseContext;
import com.at.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    //路径匹配器 支持通配符
    public  static  final AntPathMatcher PATH_MATCHER  = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //1.接收本次请求
        String requestURI = request.getRequestURI();//   /backend/index.html
        log.info("拦截的请求：{}",requestURI);
        //定义不需要处理请求路径
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/sendMsg",
                "/user/login",
                "/common/upload",
                "/common/download"
        };
        //2,判断本次请求是否需要处理
        boolean check = check(urls, requestURI);
        //3.如果不需要处理
        if(check){
            filterChain.doFilter(request,response);
            return;
        }
        //4.1判断登录状态
        if(request.getSession().getAttribute("employee")!=null){
            //获取当前登录用户id
            Long empId = (Long)request.getSession().getAttribute("employee");
            //存储到BaseContext工具类threadLocal
            BaseContext.setCurrentId(empId);

            filterChain.doFilter(request,response);
            return;
        }
//        4.2判断用户是否登录 如果已经登录则直接放行
        if (request.getSession().getAttribute("user")!=null){
            //获取当前登录用户id
            Long userId = (Long)request.getSession().getAttribute("user");
            //存储到BaseContext工具类threadLocal
            BaseContext.setCurrentId(userId);
            filterChain.doFilter(request,response);
            return;
        }

        //5.用户未登录 返回未登录信息给前端
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }

    /**
     * 路径匹配 检查本次请求是否需要放行
     * @param urls
     * @param requestURI
     * @return
     */
    public boolean check(String[] urls,String requestURI){
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if(match){
                return true;
            }
        }
        return false;

    }
}